package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.level.presenter.FiveFragmentPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.ColorEnum;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.util.CoinUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

@Route(path = RConfig.LEVEL_FRAGMENT_FIVE)
public class FiveFragment extends BaseFragment<FiveFragmentPresenter> {
    @BindView(R2.id.sellRecyclerView)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.buyRecyclerView)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.loadingLayout)
    FrameLayout loadingLayout;
    @BindView(R2.id.coin_price)
    TextView coinPrice;
    @BindView(R2.id.coin_money)
    TextView coinMoney;
    @BindView(R2.id.top)
    LinearLayout top;
    private SlimAdapter<WSFiveBean.FiveBean> sellSlimAdapter;
    private SlimAdapter<WSFiveBean.FiveBean> buySlimAdapter;
    @Autowired
    String code;
    private static final int NUM = 7;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_five;
    }

    @Override
    public FiveFragmentPresenter getPresenter() {
        return new FiveFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        initFive();
    }

    @Override
    public void initData() {
        mPresenter.getPankou(code);
        mPresenter.initSocket("depth",code);
        resetFiveUI();

        loadingLayout.setVisibility(View.GONE);
    }

    private void initFive() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        sellSlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().size() - (sellSlimAdapter.getData().indexOf(data)) + "")
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_ff5))
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : CoinUtil.keepCoinPrice(code, data.getPrice()))
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.lib_progress_red));
                            progressBar.setProgress(data.getPercent());
                        });
            }
        }).attachTo(sellRecyclerView).updateData(new ArrayList());
        buySlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : CoinUtil.keepCoinPrice(code, data.getPrice()))
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.level_03c))
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.lib_progress_green));
                            progressBar.setProgress(data.getPercent());
                        });
            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
    }


    /**
     * 更换币种
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        code = coinType.getCode();
        mPresenter.sendCode(coinType.getCode());
        resetFiveUI();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stock) {
        if (stock.getCode().equals(code) && getActivity() != null) {
            coinPrice.setText(stock.getPrice());
            coinPrice.setTextColor(ContextCompat.getColor(App.INSTANCE, stock.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
            coinMoney.setText("≈" + stock.getCnyPrice() + "CNY");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateFive(WSFiveBean wsFiveBean) {
        if (wsFiveBean.getCode().equals(code)) {
            Collections.sort(wsFiveBean.getAsks(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            Collections.sort(wsFiveBean.getBids(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            //背景百分比计算
            calculatePercentAll(wsFiveBean);
            if (wsFiveBean.getAsks().size() > NUM) {
                int startIndex = wsFiveBean.getAsks().size() - NUM;
                sellSlimAdapter.updateData(wsFiveBean.getAsks().subList(startIndex, wsFiveBean.getAsks().size()));
            } else {
                sellSlimAdapter.updateData(wsFiveBean.getAsks());
            }
            if (wsFiveBean.getBids().size() > NUM) {
                buySlimAdapter.updateData(wsFiveBean.getBids().subList(0, NUM));
            } else {
                buySlimAdapter.updateData(wsFiveBean.getBids());

            }
        }
    }

    private void calculatePercentAll(WSFiveBean wsFiveBean) {
        Double full = 0d;
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            bid.setPercent((int) (aDouble / full * 100d));
        }

        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            ask.setPercent((int) (aDouble / full * 100d));
        }

    }


    /**
     * 设置买五卖五UI --
     */
    private void resetFiveUI() {
        WSFiveBean wsFiveBean = new WSFiveBean();
        wsFiveBean.setCode(code);
        ArrayList<WSFiveBean.FiveBean> asks = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> bids = new ArrayList<>();
        for (int i = 0; i < NUM; i++) {
            asks.add(new WSFiveBean.FiveBean());
            bids.add(new WSFiveBean.FiveBean());
        }
        wsFiveBean.setAsks(asks);
        wsFiveBean.setBids(bids);
        updateFive(wsFiveBean);
    }
}
